package com.threefivework.mymall.service;

import com.threefivework.mymall.config.BaseClient;
import com.threefivework.mymall.util.JsonUtil;
import com.threefivework.mymall.util.XmlUtil;
import com.threefivework.mymall.wechat.constant.APIConstants;
import com.threefivework.mymall.wechat.constant.WXConfigConstants;
import com.threefivework.mymall.wechat.request.UnifiedOrderRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;

/**
 * descripiton:
 *
 * @author: kinson(2219945910 @ qq.com)
 * @date: 2018/6/27
 * @time: 1:13
 * @modifier:
 * @since:
 */
@Component
public class WechatClient extends BaseClient {

    private boolean useSandbox = false;

    private String getPayBaseUrl() {
        return this.useSandbox ? "https://api.mch.weixin.qq.com/sandboxnew" : "https://api.mch.weixin.qq.com";
    }

    public String test() {
        return this.doGet("/comment/test", String.class).getBody().toString();
    }

    public ResponseEntity unifiedOrder(final UnifiedOrderRequest request) throws Exception {
        //生成xml格式
        String xmlBody = XmlUtil.bean2Xml(request);
        return doUnitedOrder(getPayBaseUrl() + APIConstants.WECHAT_UNITED_ORDER_URL, xmlBody, String.class);
    }

    public Map<String, Object> getAccessToken(String code) {
        HttpClient client = new DefaultHttpClient();
        StringBuffer urlSB = new StringBuffer(APIConstants.WECHAT_ACCESS_TOKEN_URL);
        urlSB.append("?appid=").append(WXConfigConstants.APP_ID)
                .append("&secret=").append(WXConfigConstants.KEY)
                .append("&code=").append(code)
                .append("&grant_type=").append("authorization_code");
        HttpPost post = new HttpPost(urlSB.toString());
        try {
            HttpResponse httpResponse = client.execute(post);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
                return JsonUtil.getObjectFromJson(result, Map.class);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Collections.emptyMap();
    }


}
